# -*-coding=utf8-*-
import os;
import pypinyin
from mutagen.id3 import ID3, APIC, TIT2, TPE1, TALB



def SetMp3Info(mp3file, info):
    songFile = ID3(mp3file)
    # songFile['APIC'] = APIC(  # 插入封面
    #     encoding=3,
    #     mime='image/jpeg',
    #     type=3,
    #     desc=u'Cover',
    #     data=info['picData']
    # )
    songFile['TIT2'] = TIT2(  # 插入歌名
        encoding=3,
        text=info['title']
    )
    songFile['TPE1'] = TPE1(  # 插入第一演奏家、歌手、等
        encoding=3,
        text=info['artist']
    )
    # songFile['TALB'] = TALB(  # 插入专辑名
    #     encoding=3,
    #     text=info['album']
    # )
    songFile.save()


def rename():
  root_path = 'd:\\Music\\MD专辑\\'
  out_path = 'd:\\Music\\刻录\\'
  path = '经典男歌手'
  
  # 检查目录是否存在，创建必要的目录
  check_path  = out_path+path
  if(os.path.exists(check_path)):
    print('目录已经存在,注意文件是否会冲突')
  else:
    print('目录不存在，准备创建新目录'+check_path)
    os.mkdir(check_path)
    
  filelist=os.listdir(root_path+path)#该文件夹下所有的文件（包括文件夹）
  for files in filelist:#遍历所有文件
    Olddir=os.path.join(path,files);#原来的文件路径
    if os.path.isdir(Olddir):#如果是文件夹则跳过
      continue
    filename=os.path.splitext(files)[0]; #获取文件名
    #把文件名里的汉字转换成其首字母大写的全拼
    filename1  = pypinyin.pinyin(filename,style=pypinyin.NORMAL) #, 
    b = []
    for i in range(len(filename1)):
        b.append(str(filename1[i][0]).title())
    c = ''.join(b)
    Newdir = c.replace(' ','')
    print(Newdir)

    #创建一个空列表
    # filename2 = []
    # for ch in filename1:
    #   filename2.extend(ch)
    #把列表转换成没有间隔的字符串，因为文件名要以字符串形式存在
    filenameToStr = ''.join(Newdir)
    filetype=os.path.splitext(files)[1];#文件扩展名
    song_name = Newdir.split('-')
    
    Newdir=os.path.join(path,filenameToStr + filetype);#新的文件名
    print(song_name)
    
    # song_name = 
    # print(Olddir)
    # readMp3MetaInfo(Olddir)
    # print(Newdir)
    Newdir = out_path+Newdir
    Olddir = root_path+Olddir
    print(Newdir)
    
    
    cc_cmd = 'copy \"'+Olddir+'\" \"'+Newdir+'\"'
    # print(cc_cmd+'\n')
    os.system(cc_cmd)
    info = {'title': song_name[1],
            'artist': song_name[0]
          }
    SetMp3Info(Newdir, info)
    
def readMp3MetaInfo(file_path):
  print(file_path)
  songFile = ID3(file_path)

if __name__ == '__main__':
  rename()